import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';

import axios from 'axios';

const initialState = {
    nickname: '1',
    token: '2',
    avator: '3',
    permission: '4'
}

interface SigninType {
    username: string
    password: string
}

export const signin = createAsyncThunk(
    "user/signin",
    async (data: SigninType) => {
        // 模拟请求
        const resp = await axios.post('/api/signin', data)
        return resp.data.data
    }
)

const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        modifyNickname(state) {
            state.nickname = '哈哈哈哈'
        },
        modifyPermission(state, action: PayloadAction<string>) {
            state.permission = action.payload
        }
    },
    extraReducers: {
        [signin.pending.type]() {
            console.log('数据开始请求')
        },
        [signin.fulfilled.type](state, action) {
            console.log('数据请求成功', action)
            state.token = action.payload.token
        },
        [signin.rejected.type](state, action) {
            console.log('数据请求失败', action)
            state.token = ''
        }
    }
})

export default userSlice.reducer
export const { modifyNickname, modifyPermission } = userSlice.actions